package cn.xxd.xxdorderportal.controller;

import cn.xxd.AlipayService;
import cn.xxd.OrderServiceInterface;
import cn.xxd.common.AlipayConfig;
import cn.xxd.common.PrimaryGenerater;
import cn.xxd.entity.ReturnT;
import cn.xxd.entity.XxdOrder;
import cn.xxd.entity.XxdOrderTrade;
import cn.xxd.xxdssointerface.UserService;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class AlipayController {

    @Reference(version = "1.0.0", timeout = 100000)
    private AlipayService alipayService;

    @Reference(version = "1.0.0", timeout = 100000)
    private UserService userService;

    @Reference(version = "1.0.0", timeout = 100000)
    private OrderServiceInterface orderService;

    @Value("${AUTHORITY}")
    private String AUTHORITY;

    /**
     * web 订单支付
     */
    @GetMapping("getPagePay")
    public String getPagePay(String id, String items_total, HttpServletRequest request, Model model) throws Exception {


        /** 模仿数据库，从后台调数据*/
        XxdOrder xxdOrder = orderService.queryOrder(id); // 这里模仿， 实际前端传来数据

        String subject = "美妆商品";

        Double total = Double.parseDouble(items_total);

        String pay = alipayService.webPagePay(id, total.intValue(), subject); // 参数： 订单号， 金额， 商品名（暂时模拟， 不从数据库获取）

        model.addAttribute("pay", pay);

        return "pay";
    }

    /**
     * app 订单支付
     */
    @GetMapping("getAppPagePay")
    public ReturnT getAppPagePay() throws Exception {
        /** 模仿数据库，从后台调数据*/
        String outTradeNo = "131233";
        Integer totalAmount = 1000;
        String subject = "天猫超市012";

        String pay = alipayService.appPagePay(outTradeNo, totalAmount, subject);

        Object json = JSONObject.toJSON(pay);

        System.out.println(json);

        return new ReturnT(200, "success");
    }

    /**
     * 交易查询
     */
    @PostMapping("aipayQuery")
    public ReturnT alipayQuery() throws Exception {
        /**调取支付订单号*/
        String outTradeNo = "13123";

        String query = alipayService.query(outTradeNo);

        Object json = JSONObject.toJSON(query);

        /*JSONObject jObject = new JSONObject();
        jObject.get(query);*/
        return new ReturnT(200, "success");
    }

    /**
     * 退款
     *
     * @throws AlipayApiException
     */
    @GetMapping("alipayRefund")
    public ReturnT alipayRefund(
            @RequestParam("outTradeNo") String outTradeNo,
            @RequestParam(value = "outRequestNo", required = false) String outRequestNo,
            @RequestParam(value = "refundAmount", required = false) Integer refundAmount
    ) throws AlipayApiException {

        /** 调取数据*/
        //String outTradeNo = "15382028806591197";
        String refundReason = "用户不想购买";
        //refundAmount = 1;
        //outRequestNo = "22";

        String refund = alipayService.refund(outTradeNo, refundReason, refundAmount, outRequestNo);

        System.out.println(refund);

        return new ReturnT(200, "success");
    }

    /**
     * 退款查询
     *
     * @throws AlipayApiException
     */
    @PostMapping("refundQuery")
    public ReturnT refundQuery() throws AlipayApiException {

        /** 调取数据*/
        String outTradeNo = "13123";
        String outRequestNo = "2";

        String refund = alipayService.refundQuery(outTradeNo, outRequestNo);

        return new ReturnT(200, "success");

    }

    /**
     * 交易关闭
     *
     * @throws AlipayApiException
     */
    @PostMapping("alipayclose")
    public ReturnT alipaycolse() throws AlipayApiException {

        /** 调取数据*/
        String outTradeNo = "13123";

        String close = alipayService.close(outTradeNo);

        return new ReturnT(200, "success");
    }

    /**
     * 支付宝给的这个沙箱环境的接口， 经常扣款成功但没有异步请求回来， 无奈
     *
     * @param request
     * @throws AlipayApiException
     * @throws UnsupportedEncodingException
     */
    @PostMapping("notifyurl")
    public void notifyurl(HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {

        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE); //调用SDK验证签名

        // ——请在这里编写您的程序（以下代码仅作参考）——

	/* 实际验证过程建议商户务必添加以下校验：
	1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	4、验证app_id是否为该商户本身。
	*/
        if (signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

            // 金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            if (trade_status.equals("TRADE_FINISHED")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知

                // 支付宝支付: 1 支付状态修改：1
                if (orderService.modifyPayTye(1, out_trade_no) <= 0) {
                    return;
                }
                // 交易流水表处理
                XxdOrderTrade xxdOrderTrade = new XxdOrderTrade();
                String number = PrimaryGenerater.getInstance().generaterNextNumber(null);
                xxdOrderTrade.setCreate_time(new Date());
                xxdOrderTrade.setSerial_number(number);
                xxdOrderTrade.setDel("0");
                xxdOrderTrade.setOrder_id(out_trade_no);
                xxdOrderTrade.setPay_total(new BigDecimal(total_amount));
                orderService.saveTrade(xxdOrderTrade);
            }

            // out.println("success");

        } else {//验证失败
            // out.println("fail");

            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }
        //——请在这里编写您的程序（以上代码仅作参考）——
    }


    @GetMapping("test")
    public String test(HttpServletRequest request) {

        return "test";
    }

}